package zcw.com.lib_leet_code;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by 朱城委 on 2021-8-28.<br><br>
 *
 * 中等：全排列 II
 */
public class Topic47 {

    public static void main(String[] args) {
        Topic47 instance = new Topic47();

        int[] array = new int[] {1,1,2};
        System.out.println(instance.permuteUnique(array));

        array = new int[] {1,2,3};
        System.out.println(instance.permuteUnique(array));
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<Integer> list = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        boolean[] used = new boolean[nums.length];

        Arrays.sort(nums);
        helper(nums, used, list, result);
        return result;
    }

    private void helper(int[] nums, boolean[] used, List<Integer> list, List<List<Integer>> result) {
        if(list.size() == nums.length) {
            result.add(new ArrayList<>(list));
            return ;
        }

        for(int i = 0; i < nums.length; i++) {
            if(used[i] || (i > 0 && nums[i - 1] == nums[i] && !used[i - 1])) {
                continue;
            }

            list.add(nums[i]);
            used[i] = true;
            helper(nums, used, list, result);
            used[i] = false;
            list.remove(list.size() - 1);
        }
    }
} 
